﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using Actya.Core.Infrastructure;
using Newtonsoft.Json;

namespace Actya.Web.Infrastructure
{
	public class HostSettingsPersister
	{
		public HostSettings ReadSettingsFromFile(string hostConfigFile, string hostUrlFromRequest)
		{
			using (var fileStream = new FileStream(hostConfigFile, FileMode.OpenOrCreate))
			{
				using (var sr = new StreamReader(fileStream))
				{
					var hostsAsJson = sr.ReadToEnd();
					var hostsSettings = JsonConvert.DeserializeObject<List<HostSettings>>(hostsAsJson);
					if (hostsSettings != null)
					{
						var thisHostSettings = hostsSettings.SingleOrDefault(h => h.HostUrl == hostUrlFromRequest);
						if (thisHostSettings != null)
						{
							return thisHostSettings;
						}
					}
				}
			}
			return null;
		}

		public void SaveHostSettingsToFile(string hostConfigFile, HostSettings hostSettings)
		{
			List<HostSettings> hostsSettings;
			string hostsAsJson;
			using (var fileStream = new FileStream(hostConfigFile, FileMode.OpenOrCreate))
			{
				using (var sr = new StreamReader(fileStream))
				{
					hostsAsJson = sr.ReadToEnd();
					hostsSettings = JsonConvert.DeserializeObject<List<HostSettings>>(hostsAsJson) ?? new List<HostSettings>();
				}
			}
			// Remove old settings
			var previousSettings = hostsSettings.SingleOrDefault(h => h.HostUrl == hostSettings.HostUrl);
			if (previousSettings != null)
			{
				hostsSettings.Remove(previousSettings);
			}
			hostsSettings.Add(hostSettings);
			hostsAsJson = JsonConvert.SerializeObject(hostsSettings, Formatting.Indented);
			using (var sw = new StreamWriter(hostConfigFile))
			{
				sw.Write(hostsAsJson);
			}
		}
	}
}